package com.automation.ljf.strategy.impl;

import com.automation.ljf.exception.BizException;
import com.jayway.jsonpath.JsonPath;
import com.automation.ljf.domain.dataobject.CaseStepDO;
import com.automation.ljf.strategy.OperationStrategy;
import com.automation.ljf.util.DriverUtils;
import com.automation.ljf.util.ResultMessage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.springframework.stereotype.Component;

/**
 * 拖动操作
 *
 * @author lijiefeng
 * @since 2021/8/25
 */
@Component("DRAG")
public class DragStrategyImpl implements OperationStrategy {
    @Override
    public ResultMessage doOperation(ChromeDriver driver, CaseStepDO caseStepDO, String jsonData) {

        String windowHandle = driver.getWindowHandle();
        String params = JsonPath.read(jsonData, caseStepDO.getStepJsonpath());
        if (params == null){
//            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
//                    .addData("errorMsg", "无法获取json数据").addData("window", windowHandle);
            throw new BizException(3001, "jsonpath获取值为NULL");
        }
        try{
            //获取x 和 y坐标值
            String[] strings = params.split(",");
            if (!DriverUtils.isElementExist(driver, By.xpath(caseStepDO.getStepXpath()))){
                return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                        .addData("errorMsg", "元素不存在，无法定位").addData("window", windowHandle);
            }
            WebElement we = driver.findElement(By.xpath(caseStepDO.getStepXpath()));
            Actions actions = new Actions(driver);
            //标准以元素we左上角为准,拖动元素相对元素we移到右边是x是正值，左边是负值，拖动元素相对元素we移到上边是y是负值，下边是正值
            actions.dragAndDropBy(we, Integer.parseInt(strings[0]), Integer.parseInt(strings[1]))
                    .release()
                    .perform();
            Thread.sleep(2000);
        }catch (Exception e){
            return  ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "不可预知的错误").addData("window", windowHandle);
        }
        return ResultMessage.ok("操作成功").addData("window", windowHandle).addData("parameter", params);

    }
}
